<template>
  <div v-loading="detailInfoShow">
    <div class="requestAdd" v-if="!selectionMaterialShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
        v-if="activeName == 'approval' && flowInfoList.length"
        @click="handleEvaluate()"
        class="btn save"
        ><el-icon class="icon" color="#fff"> <Comment /> </el-icon
        >评论</el-button
      >
      <el-button v-if="activeName == 'approval' && flowInfoList.length" @click="handlePrint()" v-print="prints" class="btn add"
        ><el-icon class="icon" color="#fff"> <Printer /> </el-icon
        >打印</el-button
      >
        <el-button class="btn direction" @click="handleBack"
          ><el-icon class="icon" color="#fff"> <Back /> </el-icon
          >返回</el-button
        >
      </div>
      <el-tabs type="border-card"  v-model="activeName">
        <el-tab-pane label="申请信息" name="info">
          <el-collapse v-model="activeNames">
            <!-- 基础信息 -->
            <el-collapse-item name="1" v-if="!dtlShow" class="transform-down">
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title"
                  >{{
                    pageType !== "detail"
                      ? pageType === "add"
                        ? "新增"
                        : "编辑"
                      : ""
                  }}查看明细</span
                >
              </template>
              <div class="request-info">
                <el-form
                  :model="requestForm"
                  ref="requestFormRef"
                  :rules="queryRules"
                  label-width="100px"
                  v-enterToNext
                  :disabled="true"
                >
                  <el-row>
                    <el-col :span="6">
                      <el-form-item label="入库编号：">
                        <el-input
                          :disabled="true"
                          v-model="requestForm.warehousingApplyCode"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="入库批次：">
                        <el-input
                          :disabled="true"
                          style="width: 100%"
                          v-model="requestForm.batchCode"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="申请日期："
                        prop="applicantDate"
                        label-width="110"
                      >
                        <el-date-picker
                          v-model="requestForm.applicantDate"
                          format="YYYY/MM/DD"
                          class="search-input"
                          value-format="YYYY-MM-DD"
                          type="date"
                          placeholder="请选择"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="申请人：" prop="applicantId">
                        <el-select
                          v-model="requestForm.applicantId"
                          placeholder="请选择"
                          clearable
                          style="width: 100%"
                          class="search-input"
                          @change="handleUserChange"
                        >
                          <el-option
                            v-for="dict in userList"
                            :key="dict.userId"
                            :label="dict.nickName"
                            :value="dict.userId"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="申请部门：">
                        <el-input
                          :disabled="true"
                          v-model="requestForm.deptName"
                          placeholder="自动获取"
                          clearable
                          class="search-input"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="入库类型："
                        prop="warehousingApplyType"
                      >
                        <el-select
                          v-model="requestForm.warehousingApplyType"
                          placeholder="请选择入库类型"
                          @change="handleApplyTypeChange"
                          clearable
                          style="width: 100%"
                          class="search-input"
                        >
                          <el-option
                            v-for="dict in inStatusList"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <!--0-借用入库 1-租赁入库 2-盘盈入库 3-返修入库 4-采购入库 5-其他  -->
                    <el-col
                      :span="12"
                      v-if="requestForm.warehousingApplyType == 0"
                    >
                      <el-form-item label="关联请购单：" label-width="110">
                        <el-autocomplete
                          ref="request"
                          popper-class="autoclass"
                          v-model="requestForm.purchaseApplyCode"
                          :fetch-suggestions="querySearch"
                          placeholder="请选择"
                          @focus="handleAutoCompleteFocus('request')"
                          @select="handleRequestSelect"
                          style="width: 100%"
                          clearable
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div style="display: flex; width: 140px">
                                请购单编号
                              </div>
                              <div class="auto-item">申请人</div>
                              <div class="auto-item">关联项目</div>
                              <div class="auto-item">期望交付日期</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div
                                class="auto-item"
                                :title="item.purchaseApplyCode"
                                style="display: flex; width: 170px"
                              >
                                {{ item.purchaseApplyCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.applicantName"
                              >
                                {{ item.applicantName }}
                              </div>
                              <div class="auto-item" :title="item.projectName">
                                {{ item.projectName }}
                              </div>
                              <div class="auto-item" :title="item.deliveryDate">
                                {{ item.deliveryDate }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>

                    <el-col
                      :span="12"
                      v-if="requestForm.warehousingApplyType == 3"
                    >
                      <el-form-item label="关联出库单：" label-width="110">
                        <el-autocomplete
                          popper-class="autoclass"
                          ref="outOrder"
                          v-model="requestForm.deliveryApplyCode"
                          :fetch-suggestions="querySearch"
                          placeholder="请选择"
                          @focus="handleAutoCompleteFocus('outOrder')"
                          @select="handleOutOrderSelect"
                          style="width: 100%"
                          clearable
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div style="display: flex; width: 140px">
                                出库单编号
                              </div>
                              <div class="auto-item">申请人</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div
                                class="auto-item"
                                :title="item.deliveryApplyCode"
                                style="display: flex; width: 170px"
                              >
                                {{ item.deliveryApplyCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.applicantName"
                              >
                                {{ item.applicantName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>
                    <el-col
                      :span="12"
                      v-if="
                        requestForm.warehousingApplyType == 1 ||
                        requestForm.warehousingApplyType == 4
                      "
                    >
                      <el-form-item label="关联合同：" label-width="110">
                        <el-autocomplete
                          popper-class="autoclass"
                          ref="contract"
                          v-model="requestForm.contractCode"
                          :fetch-suggestions="querySearch"
                          placeholder="请选择"
                          @focus="handleAutoCompleteFocus('contract')"
                          @select="handleContractSelect"
                          style="width: 100%"
                          clearable
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div style="display: flex; width: 170px">
                                合同编号
                              </div>
                              <div class="auto-item">合同名称</div>
                              <div class="auto-item">供应商</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div
                                class="auto-item"
                                :title="item.purchaseContractCode"
                                style="display: flex; width: 170px"
                              >
                                {{ item.purchaseContractCode }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.purchaseContractName"
                              >
                                {{ item.purchaseContractName }}
                              </div>
                              <div class="auto-item" :title="item.supplierName">
                                {{ item.supplierName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="关联项目：">
                        <el-autocomplete
                          popper-class="autoclass"
                          ref="project"
                          v-model="requestForm.projectName"
                          :fetch-suggestions="querySearch"
                          placeholder="请选择"
                          @focus="handleAutoCompleteFocus('project')"
                          @select="handleProjectSelect"
                          style="width: 100%"
                          clearable
                        >
                          <template #default="{ item }">
                            <!-- <div class="auto-top"> -->
                            <div class="auto-top" style="display: flex">
                              <div style="display: flex; width: 140px">
                                项目编号
                              </div>
                              <div class="auto-item">项目名称</div>
                              <div class="auto-item">项目类别</div>
                              <div class="auto-item">项目类型</div>
                            </div>
                            <div style="display: flex; width: 500px">
                              <div
                                class="auto-item"
                                :title="item.projectCode"
                                style="display: flex; width: 170px"
                              >
                                {{ item.projectCode }}
                              </div>
                              <div class="auto-item" :title="item.projectName">
                                {{ item.projectName }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.projectCategoryName"
                              >
                                {{ item.projectCategoryName }}
                              </div>
                              <div
                                class="auto-item"
                                :title="item.projectTypeName"
                              >
                                {{ item.projectTypeName }}
                              </div>
                            </div>
                          </template>
                        </el-autocomplete>
                      </el-form-item>
                    </el-col>

                    <el-col
                  :span="12"
                  v-if="
                    requestForm.warehousingApplyType == 1 ||
                    requestForm.warehousingApplyType == 4
                  "
                >
                  <el-form-item label="供应商：">
                    <el-input
                      style="width: 100%"
                      v-model="requestForm.supplierName"
                      placeholder=""
                      type="text"
                      clearable
                      :disabled="true"
                    />
                  </el-form-item>
                </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="备注：">
                        <el-input
                          style="width: 100%"
                          v-model="requestForm.remarks"
                          placeholder=""
                          type="textarea"
                          clearable
                          maxlength="2000"
                        />
                      </el-form-item>
                    </el-col>

                    <el-col :span="6">
                      <el-form-item
                        label="附件："
                        prop="businessLicense"
                        label-width="110"
                      >
                        <Upload
                          :fileList="requestForm.fileList"
                          :isFull="true"
                          :isCanDelete="false"
                          :disabled="true"
                          :showButton="true"
                          @success="(result) => uploadSuccess(result, 8)"
                          @deleteFile="(result) => uploadRemove(result, 8)"
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </el-collapse-item>
            <!-- 添加物料 -->

            <!-- 联系人列表 -->
            <el-collapse-item
              name="3"
              style="position: relative"
              :class="!dtlShow ? 'transform-down' : ''"
            >
              <template #title>
                <span class="circle"></span>
                <span class="collapse-title">物料列表</span>
                <div class="nofixed-search-button button-position">
                  <el-button
                    style="width: 150px"
                    class="btn submit"
                    @click.stop="handleQrcode()"
                    ><el-icon class="icon" color="#fff"> </el-icon
                    >下载全部二维码</el-button
                  >
                </div>
              </template>
              <div class="contact-info">
                <!-- 表格数据 -->
                <el-table
                  :data="requestForm.dtlList"
                  border
                  :height="'280px'"
                  :header-cell-style="{ 'text-align': 'center' }"
                  show-summary
                  sum-text="合计"
                  :summary-method="getSummaries"
                >
                  <el-table-column
                    label="主设备物资序列号"
                    prop="materialNumber"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="序号"
                    type="index"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="物料编号"
                    prop="materialCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  >
                    <template #default="{ row }">
                      <span>{{
                        row.materialCode ? row.materialCode : "--"
                      }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="物料名称"
                    prop="materialName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="出厂型号"
                    prop="factoryCode"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="技术参数"
                    prop="technologyParameter"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="单位"
                    prop="materialUnitName"
                    :show-overflow-tooltip="true"
                    min-width="160"
                  />
                  <el-table-column
                    label="采购单价（元）"
                    prop="purchasePrice"
                    :show-overflow-tooltip="true"
                    min-width="120"
                  />
                  <el-table-column
                    label="申请入库数量"
                    prop="warehousingQuantity"
                    min-width="160"
                  >
                  </el-table-column>
                  <el-table-column
                    label="已入库数量"
                    prop="inQty"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库编号"
                    prop="warehousingApplyCode"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库批次"
                    prop="batchCode"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库人"
                    prop="applicantName"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库部门"
                    prop="deptName"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库日期"
                    prop="applicantDate"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="入库仓位"
                    prop="warehouseCode"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="授权有效期"
                    prop="validityPeriod"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column
                    label="厂家质保期"
                    prop="expireDate"
                    min-width="120"
                  >
                  </el-table-column>
                  <el-table-column label="入库图片" prop="" min-width="120">
                    <template #default="{ row }">
                      <div v-if="row.fileList" class="image-content">
                        <el-image
                          v-for="(item, index) in row.fileList"
                          :key="index"
                          :preview-teleported="true"
                          style="width: 50px; height: 50px; margin-right: 5px"
                          :src="item.url"
                          :preview-src-list="showImg(item.url)"
                        >
                          <template #error>
                            <div class="image-slot">
                              <el-icon><icon-picture /></el-icon>
                            </div>
                          </template>
                        </el-image>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="remarks" min-width="120">
                  </el-table-column>
                </el-table>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="审批进度" name="approval">
         <template v-if="requestForm.auditList.length">
          <div class="contact-info"  id="print-iframe" >
            <!-- 步骤栏 -->
            <el-steps
              :class="flowInfoList.length>7 ? 'BigSteps' : 'SmallSteps'"
              :active="flowingStep"
              
              finish-status="success"
            >
              <el-step v-for="(item, index) in flowInfoList" :key="index">
                <template #title>{{ item.name }}</template>
                <template #description>
                  <div>
                    <p class="ription">{{ item.auditDate }}</p>
                    <p class="ription">{{ item.auditEmp }}</p>
                  </div>
                </template>
              </el-step>
            </el-steps>
            <!-- 表格数据 -->
            <el-table
              :data="requestForm.auditList"
              border
              :height="'100%'"
              :header-cell-style="{ 'text-align': 'center' }"
              sum-text=""
            >
              <!-- 操作模式 -->
              <el-table-column label="流程节点" prop="name" min-width="120">
              </el-table-column>
              <el-table-column
                label="审核人"
                prop="createUserName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核时间"
                prop="createTime"
                min-width="120"
              >
              </el-table-column>
              <el-table-column
                label="审核意见"
                prop="resultName"
                min-width="120"
              >
              </el-table-column>
              <el-table-column label="审核备注" prop="remark" min-width="120">
              </el-table-column>
            </el-table>
          </div>
           <!-- 评论 -->
           <el-table
            style="margin-top: 60px"
            :data="evaluateList"
            border
            :height="'100%'"
            :header-cell-style="{ 'text-align': 'center' }"
            sum-text=""
          >
            <!-- 操作模式 -->
            <el-table-column label="评论内容" prop="content" min-width="500">
            </el-table-column>
            <el-table-column
              label="评论人"
              prop="createUserName"
              min-width="120"
            >
            </el-table-column>
            <el-table-column label="评论时间" prop="createTime" min-width="120">
            </el-table-column>
          </el-table>
         </template>
          <div v-else>
            暂无审核
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <SelectionMaterial
      ref="selectionMaterialRef"
      v-if="selectionMaterialShow"
      v-model:selectionMaterialShow="selectionMaterialShow"
      @submitChoose="handleSelectMaterial"
    />
  </div>

  <el-dialog
    v-model="dialogVisible"
    title="主设备序列号"
    width="36%"
    :close-on-click-modal="false"
  >
    <QrCodeInfo :qrcodeData="qrcodeData" />
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
  <el-dialog
      :title="''"
      v-model="evaluateDialogShow"
      width="600px"
      append-to-body
    >
      <el-form-item label="评论内容：" label-width="90">
        <el-input
          style="width: 100%"
          v-model="evaluateInfo"
          placeholder=""
          type="textarea"
          rows="5"
          maxlength="500"
          clearable
        />
      </el-form-item>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="saveEvaluate()"
            >保存</el-button
          >

          <el-button style="background-color: #fff" @click="closeEvaluate()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
</template>

<script setup>
import SelectionMaterial from "./selectionMaterial";
import Upload from "@/components/Upload/index";
import { addEvaluateApi, getEvaluateListApi } from "@/api/pub.js";
import { getUserListApi } from "@/api/information/customer";
import QrCodeInfo from "@/components/qrCode/index";
import { getDictsApi } from "@/api/dict";
import { autoComplete } from "@/api/pub";
import {
  showAddTemp,
  saveAddWarehouseApply,
  showEditTemp,
  saveEditWarehouseApply,
} from "@/api/stock/inorder";
import { ElMessage, ElMessageBox } from "element-plus";
const route = useRoute();
const emit = defineEmits([
  // 客户新增组件显隐
  "dtlShow",
  // 更新客户新增组件显隐
  "update:dtlShow",
  // 刷新父组件表格数据
  "refreshList",
]);

//控制查看二维码弹窗
const dialogVisible = ref(false);
//主设备物资序列号数据
const qrcodeData = ref([]);

const props = defineProps({
  // 操作类型
  pageType: {
    type: String,
    default: "add",
  },
});
const activeName = ref('info')
// 折叠栏默认展开
const activeNames = ref(["1", "2", "3"]);
// 客户表单引用
const requestFormRef = ref();
// 联系人表单引用
const contactFormRef = ref();
// 联系人操作类型
const operateType = ref("");
// 新增联系人表单显隐
const dtlShow = ref(false);
// 选择物料显隐
const selectionMaterialShow = ref(false);
// 详情加载效果
const detailInfoShow = ref(false);
// 输入框引用
const refInput = ref();
// 下拉框引用
const refSelect = ref();
// 联系人当前索引(编辑联系人使用)
const tableIndex = ref(null);
// 采购类型列表
const typeList = ref([]);
// 单位列表
const unitList = ref([]);
// 入库类型状态
const inStatusList = ref([]);
//审核进度数据
const flowInfoList = ref([]);
//当前进度
const flowingStep = ref(0);

// 评论
const evaluateDialogShow = ref(false);
// 评论内容
const evaluateInfo = ref("");
// 评论列表
const evaluateList = ref([]);

// 客户表单数据模板
const requestFormTemplate = {
  warehouseApplyId: null,
  remarks: null,
  status: null,
  warehousingApplyCode: null,
  batchCode: null,
  applicantId: null,
  applicantDate: null,
  warehousingApplyType: null,
  purchaseApplyId: null,
  purchaseApplyCode: null,
  deliveryOrderId: null,
  deliveryApplyCode: null,
  relationContractId: null,
  contractCode: null,
  projectId: null,
  projectName: null,
  warehousingCheckStatus: null,
  deptId: null,
  deptName: null,
  type: null,

  fileList: [],
  dtlList: [],
  // inList: [],
  auditList: [],
};
// 联系人表单数据模板

const data = reactive({
  // 客户表单
  requestForm: JSON.parse(JSON.stringify(requestFormTemplate)),

  // 客户表单校验规则
  queryRules: {
    applicantDate: [
      { required: true, message: "请选择申请日期", trigger: "change" },
    ],
    applicantId: [
      { required: true, message: "请选择申请人", trigger: "change" },
    ],
    warehousingApplyType: [
      { required: true, message: "请选择入库类型", trigger: "change" },
    ],
  },
  autoType: "",

  // 用户列表
  userList: [],
});

const { requestForm, queryRules, userList, autoType } = toRefs(data);

import print from "vue3-print-nb";

// 使用自定义指令
const vPrint = print;
const printFlag = ref(false);

let prints = {
  id: "print-iframe",
  popTitle: "配置页眉标题", // 打印配置页上方的标题
  extraHead: "", // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
  preview: false, // 是否启动预览模式，默认是false
  previewTitle: "预览的标题", // 打印预览的标题
  previewPrintBtnLabel: "预览结束，开始打印", // 打印预览的标题下方的按钮文本，点击可进入打印
  zIndex: 20002, // 预览窗口的z-index，默认是20002，最好比默认值更高
  previewBeforeOpenCallback() {
    console.log("正在加载预览窗口！");
  }, // 预览窗口打开之前的callback
  previewOpenCallback() {
    console.log("已经加载完预览窗口，预览打开了！");
  }, // 预览窗口打开时的callback
  // 开始打印之前的callback
  beforeOpenCallback() {
    
    console.log("开始打印之前！");
   
  },
  openCallback() {
    console.log("执行打印了！");
  }, // 调用打印时的callback
  closeCallback() {
    console.log("关闭了打印工具！");
    printFlag.value= false
  }, // 关闭打印的callback(无法区分确认or取消)
  clickMounted() {
    console.log("点击v-print绑定的按钮了！");
    
  },
  standard: "",
  extarCss: "",
};

const handlePrint = ()=>{
  printFlag.value = true
}

// 处理评论按钮点击
const handleEvaluate = () => {
  evaluateDialogShow.value = true;
};

// 保存评论
const saveEvaluate = async () => {
  if (!evaluateInfo.value) return ElMessage.info("请输入评论内容！");
  const data = {
    businessId: requestForm.value.warehouseApplyId,
    content: evaluateInfo.value,
    modelType: 8,
  };
  const result = await addEvaluateApi(data);
  if (result.code === 200) {
    ElMessage.success(result.msg);
    evaluateDialogShow.value = false;
    evaluateInfo.value = "";
    getEvaluateList()
  }
};

// 关闭评论弹窗
const closeEvaluate = () => {
  evaluateDialogShow.value = false;
  evaluateInfo.value = "";
};

// 获取评价列表
const getEvaluateList = async () => {
  const data = {
    businessId: requestForm.value.warehouseApplyId,
    modelType: 8,
  };
  const result = await getEvaluateListApi(data);
  evaluateList.value = result.data || []
};

/**
 * @description: 保存
 * @param {Object} requestFormRef 客户表单引用
 */
// const handleAddSave = async (requestFormRef, type) => {
//   if (!requestFormRef) return;
//   if (requestForm.value.warehousingApplyType == 0) {
//     if (
//       requestForm.value.purchaseApplyId == null ||
//       requestForm.value.purchaseApplyId == ""
//     ) {
//       ElMessage.error("借用入库关联请购单不能为空");
//       return;
//     }
//   } else if (requestForm.value.warehousingApplyType == 3) {
//     if (
//       requestForm.value.deliveryOrderId == null ||
//       requestForm.value.deliveryOrderId == ""
//     ) {
//       ElMessage.error("返修入库关联出库单不能为空");
//       return;
//     }
//   } else if (requestForm.value.warehousingApplyType == 1) {
//     if (
//       requestForm.value.relationContractId == null ||
//       requestForm.value.relationContractId == ""
//     ) {
//       ElMessage.error("租赁入库关联合同不能为空");
//       return;
//     }
//   }
//   await requestFormRef.validate(async (valid, fields) => {
//     if (valid) {
//       ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//         type: "warning",
//         confirmButtonClass: "confirmBtnClass",
//         cancelButtonClass: "cancelBtnClass",
//       })
//         .then(async () => {
//           requestForm.value.type = type;
//           let res;

//           // 新增客户
//           res = await saveAddWarehouseApply(requestForm.value);
//           /* else {
//             // 编辑客户
//             res = await editRequestApi(requestForm.value);
//           }*/

//           if (res.code === 200) {
//             emit("update:dtlShow", false);
//             emit("refreshList", false);
//             ElMessage.success(res.msg);
//             requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
//           } else {
//             ElMessage.error(res.msg);
//           }
//         })
//         .catch(() => {});
//     }
//   });
// };

// const handleEditSave = async (requestFormRef, type) => {
//   if (!requestFormRef) return;
//   if (requestForm.value.warehousingApplyType == 0) {
//     if (
//       requestForm.value.purchaseApplyId == null ||
//       requestForm.value.purchaseApplyId == ""
//     ) {
//       ElMessage.error("借用入库关联请购单不能为空");
//       return;
//     }
//   } else if (requestForm.value.warehousingApplyType == 3) {
//     if (
//       requestForm.value.deliveryOrderId == null ||
//       requestForm.value.deliveryOrderId == ""
//     ) {
//       ElMessage.error("返修入库关联出库单不能为空");
//       return;
//     }
//   } else if (requestForm.value.warehousingApplyType == 1) {
//     if (
//       requestForm.value.relationContractId == null ||
//       requestForm.value.relationContractId == ""
//     ) {
//       ElMessage.error("租赁入库关联合同不能为空");
//       return;
//     }
//   }
//   await requestFormRef.validate(async (valid, fields) => {
//     if (valid) {
//       ElMessageBox.confirm("确定保存以上数据吗？", "提示", {
//         confirmButtonText: "确定",
//         cancelButtonText: "取消",
//         type: "warning",
//         confirmButtonClass: "confirmBtnClass",
//         cancelButtonClass: "cancelBtnClass",
//       })
//         .then(async () => {
//           requestForm.value.type = type;
//           let res;

//           // 新增客户
//           res = await saveEditWarehouseApply(requestForm.value);
//           /* else {
//             // 编辑客户
//             res = await editRequestApi(requestForm.value);
//           }*/

//           if (res.code === 200) {
//             emit("update:dtlShow", false);
//             emit("refreshList", false);
//             ElMessage.success(res.msg);
//             requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
//           } else {
//             ElMessage.error(res.msg);
//           }
//         })
//         .catch(() => {});
//     }
//   });
// };

/**
 * @description: 返回
 */
const handleBack = () => {
  emit("update:dtlShow", false);
  emit("refreshList", false);
  requestForm.value = JSON.parse(JSON.stringify(requestFormTemplate));
};

/**
 * @description: 处理选择物料
 */
// const handleMaterial = () => {
//   selectionMaterialShow.value = true;
// };

/**
 * @description: 处理物料选择
 */
const handleSelectMaterial = (value) => {
  if (value) {
    selectionMaterialShow.value = false;

    requestForm.value.dtlList.push(JSON.parse(JSON.stringify(value)));
  } else {
    ElMessage.info("请选择物料");
  }
};

const showImg = (img) => {
  let imgArr = [];
  imgArr.push(img);
  return imgArr;
};

const handleAutoCompleteFocus = (value) => {
  autoType.value = value;
};

/**
 * @description: 处理供应商、生产厂家选择
 */
const handleProjectSelect = (value) => {
  requestForm.value.projectId = value.id;
  requestForm.value.projectName = value.projectName;
};

const handleRequestSelect = (value) => {
  requestForm.value.purchaseApplyId = value.id;
  requestForm.value.purchaseApplyCode = value.purchaseApplyCode;
};

const handleContractSelect = (value) => {
  requestForm.value.relationContractId = value.id;
  requestForm.value.contractCode = value.purchaseContractCode;
};

const handleOutOrderSelect = (value) => {
  requestForm.value.deliveryOrderId = value.id;
  requestForm.value.deliveryApplyCode = value.deliveryApplyCode;
};

const querySearch = (queryStr, cb) => {
  if (autoType.value == "project") {
    requestForm.value.projectId = "";
    requestForm.value.projectName = "";
  }

  if (autoType.value == "request") {
    requestForm.value.purchaseApplyId = "";
    requestForm.value.purchaseApplyCode = "";
  }

  if (autoType.value == "contract") {
    requestForm.value.relationContractId = "";
    requestForm.value.contractCode = "";
    requestForm.value.supplierName = "";
  }

  if (autoType.value == "outOrder") {
    requestForm.value.deliveryOrderId = "";
    requestForm.value.deliveryApplyCode = "";
  }

  if (queryStr === "null") {
    queryStr = null;
  }
  autoComplete(queryStr, autoType.value).then((response) => {
    const list = response;

    cb(list);
  });
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleUserChange = (value) => {
  if (value) {
    const selectUser = userList.value.find((item) => item.userId === value);
    if (selectUser) {
      requestForm.value.deptName = selectUser.dept.deptName;
    }
  } else {
    requestForm.value.deptName = "";
  }
};

/**
 * @description: 处理人员选择
 * @param {Number} value 选择值
 */
const handleApplyTypeChange = (value) => {
  requestForm.value.purchaseApplyId = "";
  requestForm.value.purchaseApplyCode = "";

  requestForm.value.relationContractId = "";
  requestForm.value.contractCode = "";

  requestForm.value.deliveryOrderId = "";
  requestForm.value.deliveryApplyCode = "";
  requestForm.value.dtlList = [];
};

/**
 * @description: 文件上传成功处理
 * @param {Object} response 文件信息
 */
function uploadSuccess(response) {
  requestForm.value.fileList.push({ ...response, businessType: 8 });
}

/**
 * @description: 删除文件
 * @param {Number} index 当前文件索引
 */
function uploadRemove(index) {
  requestForm.value.fileList.splice(index, 1);
}

/**
 * @description: 处理合计
 */
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    // 只对amount这一列进行总计核算。
    if (
      column.property === "warehousingQuantity" ||
      column.property === "inQty"
    ) {
      if (!values.every((value) => isNaN(value))) {
        sums[index] = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          } else {
            return prev;
          }
        }, 0);
        // sums[index] = sums[index].toFixed(2); // 保留2位小数，解决小数列合计精度缺失的问题
        // sums[index] += "元";
      } else {
        sums[index] = "";
      }
    }
  });

  return sums;
};

/**
 * @description: 处理联系人表格操作
 * @param {String} type 操作类型
 * @param {Object} row  当前行数据
 * @param {Number} tabIndex 表格当前索引
 */
const handleOperate = (type, row, tabIndex) => {
  requestForm.value.dtlList.splice(tabIndex, 1);
};

/**
 * @description: 打开新增页面
 * @param {Number} id
 */
const showAdd = async () => {
  try {
    await showAddTemp(1).then((res) => {
      if (res.code === 200) {
        nextTick(() => {
          requestForm.value = res.data;
        });
      }
    });

    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 处理详情信息
 * @param {Number} id
 */
const showEdit = async (row) => {
  try {
    await showEditTemp({ id: row.id, type: row.checkStatus }).then((res) => {
      if (res.code === 200) {
        nextTick(() => {
          requestForm.value = res.data;
          getEvaluateList()
          if(res.data.auditList.length){
            flowInfoList.value = res.data.auditList[0].chartVo.flowList;
            flowingStep.value = res.data.auditList[0].chartVo.flowingStep;
          }
        });
      }
    });
    detailInfoShow.value = false;
  } catch (error) {
    detailInfoShow.value = false;
  }
};

/**
 * @description: 查看主设备物资序列号
 */
const handleQrcode = async () => {
  if (requestForm.value.dtlList.length > 0) {
    qrcodeData.value = [];

    requestForm.value.dtlList.forEach((item) => {
      if (item.materialNumber)
        qrcodeData.value.push({
          materialNumber: item.materialNumber,
        });
    });
    if (qrcodeData.value.length > 0) {
      dialogVisible.value = true;
    } else {
      ElMessage.error("暂无数据");
    }
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  // 类型
  await getDictsApi("erp_applicant_type").then((res) => {
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });

  // 入库类型
  await getDictsApi("erp_warehousing_apply_type").then((res) => {
    if (res.code === 200) {
      inStatusList.value = res.data;
    }
  });

  await getUserListApi({}).then((res) => {
    if (res.length > 0) {
      userList.value = res;
    }
  });
}

onMounted(() => {
  getDicts();
});

defineExpose({
  showEdit,
  showAdd,
});
</script>
<style lang="scss" scoped>
.requestAdd {
  padding: 20px 20px;
  width: 100%;
  height: 100%;
  .request-info {
    padding: 20px 20px 5px 20px;
    background-color: #f0f0f0;
    margin: 10px 0;
  }
  .contact-info {
    padding-top: 20px;
    .ription {
      color: #8f8f8f;
      line-height: 16px;
      font-size: 12px;
    }
    :deep(.el-step__head.is-success) {
      color: #3399ff;
      border-color: #3399ff;
      position: relative;
    }
    :deep(.el-step__title) {
      font-size: 16px;
      line-height: 38px;
      position: absolute;
      top: -38px;
      width: 140px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.el-step__title.is-success) {
      color: #3399ff;
    }
  }

  :deep(.el-table) {
    th.el-table__cell {
      background: #f8f8f8 !important;
    }
  }
  :deep(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
    width: 268px !important;
    height: 34px !important;
  }
  .search-input {
    width: 268px;
    height: 34px;
  }
  .image-content {
    width: 100%;
    line-height: 0px;
    overflow: auto;
  }

  :deep(.search-button .btn) {
    .el-icon {
      display: none;
    }
  }
}
.auto-top {
  width: 100%;
  position: absolute;
  top: 0px;
  display: flex;
  font-weight: bold;
}
.auto-item {
  width: 125px;
  text-align: center;
  white-space: nowrap; /* 禁止换行 */
  overflow: hidden; /* 隐藏超出部分 */
  text-overflow: ellipsis; /* 使用省略号表示超出部分 */
}
.el-autocomplete .el-autocomplete-suggestion {
  max-height: 200px; /* 设置最大高度 */
  overflow-y: auto; /* 超出高度时显示滚动条 */
}
.el-table {
  border: var(--el-table-border);
}
</style>
